import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RestService } from '../../app/services/rest.service';

import * as _ from 'lodash';

@Component({
  selector: 'page-search',
  templateUrl: 'search.html'
})
export class SearchPage {
  user: any = {};
  condition = 'nurse';
  nurses = [];
  buildings = [];
  levels = [];
  rooms = [];

  persons = [];
  allPersons = [];
  filter: any;

  pNumberPerPage = 30;
  position = 0;

  constructor(public navCtrl: NavController, private rest: RestService) {
    this.user = this.rest.getUser();
    this.filter = this.rest.getFilter();
  }

  checkNurse() {
    this.rest.getWithParams('/data/nurse/search/findall', {
      institutionId: this.user.instId
    }).subscribe(resp => {
      resp['_embedded']['nurses'].forEach(nurse => {
        const index = _.findIndex(this.filter.nurses, {id: nurse.id});
        nurse['checked'] = index > -1;
        this.nurses.push(nurse);
      });
    }, message => {
    });
  }

  checkBuilding() {
    this.rest.getWithParams('/data/building/search/findall', {
      institutionId: this.user.instId
    }).subscribe(resp => {
      resp['_embedded']['buildings'].forEach(building => {
        const index = _.findIndex(this.filter.buildings, {id: building.id});
        building['checked'] = index > -1;
        this.buildings.push(building);

        this.rest.get('/data/building/' + building.id + '/levels').subscribe(resp => {
          resp['_embedded']['levels'].forEach(level => {
            level['match'] = building.buildingName + '##' + level.levelName;
            level['display'] = building.buildingName
            const index = _.findIndex(this.filter.levels, {id: level.id});
            level['checked'] = index > -1;
            this.levels.push(level);

            this.rest.get('/data/level/' + level.id + '/rooms').subscribe(resp => {
              resp['_embedded']['rooms'].forEach(room => {
                room['match'] = level.match + '##' + room.roomName;
                room['display'] = level.display + ' - ' + level.levelName;
                const index = _.findIndex(this.filter.rooms, {id: room.id});
                room['checked'] = index > -1;
                this.rooms.push(room);
              });
            });
          });
        });
      })
    }, message => {
    });
  }

  checkPerson() {
    this.rest.getWithParams('/data/person/search/monitorAllIn', {
      institutionId: this.user.instId,
      checkoutTime: 1
    }).subscribe(resp => {
      resp['_embedded']['persons'].forEach(person => {
        const index = _.findIndex(this.filter.persons, {id: person.id});
        person['checked'] = index > -1;
        this.allPersons.push(person);
      });

      for (let i = 0; i < this.allPersons.length && i < this.pNumberPerPage; i++) {
        this.persons.push(this.allPersons[i]);
        this.position = i + 1;
      }
    }, message => {
    });
  }

  getBedString(person) {
    if (person.bedString) {
      return person.bedString.replace(/##/g, ' - ');
    } else {
      return '';
    }
  }

  doInfinite(infiniteScroll) {
    setTimeout(() => {
      for (let i = this.position, j = 0; i < this.allPersons.length && j < this.pNumberPerPage; i++, j++) {
        this.persons.push(this.allPersons[i]);
        this.position = i + 1;
      }

      infiniteScroll.complete();
    }, 500);
  }

  ionViewDidEnter() {
    this.checkPerson();
    this.checkNurse();
    this.checkBuilding();
  }

  ionViewWillLeave() {
    const checkedNurses = [];
    this.nurses.forEach(nurse => {
      if (nurse.checked) {
        checkedNurses.push({
          id: nurse.id,
        });
      }
    });

    const checkedBuildings = [];
    this.buildings.forEach(item => {
      if (item.checked) {
        checkedBuildings.push({
          id: item.id,
          match: item.buildingName
        });
      }
    });

    const checkedLevels = [];
    this.levels.forEach(item => {
      if (item.checked) {
        checkedLevels.push({
          id: item.id,
          match: item.match
        });
      }
    });

    const checkedRooms = [];
    this.rooms.forEach(item => {
      if (item.checked) {
        checkedRooms.push({
          id: item.id,
          match: item.match
        });
      }
    });

    const checkedPersons = [];
    this.allPersons.forEach(item => {
      if (item.checked) {
        checkedPersons.push({
          id: item.id
        });
      }
    });

    this.rest.saveFilter({
      persons: checkedPersons,
      nurses: checkedNurses,
      buildings: checkedBuildings,
      levels: checkedLevels,
      rooms: checkedRooms
    });
  }

  navBack() {
    this.navCtrl.pop();
  }
}
